package com.qdsgjsfk.vision.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.exception.BleException;
import com.qdsgjsfk.vision.R;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.base.BaseFragment;
import com.qdsgjsfk.vision.eventbus.BlueTooth;
import com.qdsgjsfk.vision.eventbus.ModeChange;
import com.qdsgjsfk.vision.eventbus.SocketInput;
import com.qdsgjsfk.vision.eventbus.StartVision;
import com.qdsgjsfk.vision.model.Msg;
import com.qdsgjsfk.vision.service.BluetoothLeService;
import com.qdsgjsfk.vision.service.SocketService;
import com.qdsgjsfk.vision.ui.DeviceTypeActivity;
import com.qdsgjsfk.vision.ui.StudentDetailActivity;
import com.qdsgjsfk.vision.ui.StudentDetailOtherActivity;
import com.qdsgjsfk.vision.ui.dialog.PeripheralTipDialog;
import com.qdsgjsfk.vision.ui.dialog.QualifiedDialog;
import com.qdsgjsfk.vision.ui.dialog.RemarkDialog;
import com.qdsgjsfk.vision.ui.dialog.VisionDialog;
import com.qdsgjsfk.vision.ui.dialog.VisionSelfDialog;
import com.qdsgjsfk.vision.util.Constant;
import com.qdsgjsfk.vision.util.NetUtil;
import com.qdsgjsfk.vision.util.ToastUtil;
import com.qdsgjsfk.vision.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.response.BaseResponse;
import com.rest.response.QualifiedResponse;
import com.rest.response.StudentInfoResponse;
import com.rest.response.StudentSEQ;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.wj.android.colorcardview.CardView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;
import util.PreferencesHelper;
import util.ServiceUtil;

/**
 * Created by HP on 2018/10/7.
 */

public class VisionFragment extends BaseFragment {
    @BindView(R.id.osVision)
    TextView osVision;
    @BindView(R.id.odVision)
    TextView odVision;
    @BindView(R.id.osEsysight)
    TextView osEsysight;
    @BindView(R.id.odEyesight)
    TextView odEyesight;
    @BindView(R.id.btn_confirm)
    TextView btn_confirm;
    @BindView(R.id.stuName)
    TextView stuName;
    @BindView(R.id.tv_remark)
    TextView tv_remark;
    @BindView(R.id.odOk)
    EditText edt_odOk;
    @BindView(R.id.osOk)
    EditText edt_osOk;
    @BindView(R.id.tv_ok_remark)
    TextView tv_ok_remark;
    @BindView(R.id.edt_kuangjia_right)
    EditText edt_kuangjia_right;
    @BindView(R.id.edt_kuangjia_left)
    EditText edt_kuangjia_left;
    @BindView(R.id.edt_yinxing_right)
    EditText edt_yinxing_right;
    @BindView(R.id.edt_yinxing_left)
    EditText edt_yinxing_left;
    @BindView(R.id.tv_glass_remark)
    TextView tv_glass_remark;
    @BindView(R.id.btn_next)
    TextView btn_next;
    @BindView(R.id.container_ok)
    CardView container_ok;
    @BindView(R.id.container_od)
    CardView container_od;
    @BindView(R.id.container_luoyan)
    CardView container_luoyan;
    @BindView(R.id.tv_examiner)
    TextView tv_examiner;
    @BindView(R.id.more)
    ImageView more;
    @BindView(R.id.btn_remark)
    LinearLayout btnRemark;
    @BindView(R.id.tv_examiner_time)
    TextView tvExaminerTime;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.tv_lastVision)
    TextView tv_lastVision;
    @BindView(R.id.container_kuangjia)
    CardView container_kuangjia;
    @BindView(R.id.container_yinxing)
    CardView container_yinxing;
    @BindView(R.id.btn_start)
    TextView btn_start;
    @BindView(R.id.group_glasses_type)
    RadioGroup radioGroup;
    @BindView(R.id.rbtn_no_glass)
    RadioButton rbtnNoGlass;
    @BindView(R.id.rbtn_frame_glass)
    RadioButton rbtnFrameGlass;
    @BindView(R.id.rbtn_contact_lenses)
    RadioButton rbtnContactLenses;
    @BindView(R.id.rbtn_ok_glass)
    RadioButton rbtnOkGlass;
    Unbinder unbinder;
    private boolean isEmptyRemark = true;
    String studentId;
    private VisionDialog mVisionDialog;
    private VisionSelfDialog mVisionSelfDialog;
    private QualifiedDialog mQualifiedDialog;
    private RemarkDialog mRemarkDialog;
    private PeripheralTipDialog peripheralTipDialog;
    private String taskId, taskType, tempData = "";
    String manual = "0";
    ProgressDialog progressDialog;
    int isFrameglass = 0, isContactlenses = 0, isOkglasses = 0, bleCount = 0;
    boolean daijing1, daijing2, daijing3, isDataChange = false;
    private StudentInfoResponse.StudentLastTaskInfo studentLastTaskInfo;
    Activity activity;
    String rightDiopter = "", leftDiopter = "";

    public static VisionFragment newInstance(String studentId, String taskId, String type) {
        Bundle args = new Bundle();
        args.putString( "studentId", studentId );
        args.putString( "taskId", taskId );
        args.putString( "type", type );
        VisionFragment fragment = new VisionFragment();
        fragment.setArguments( args );
        return fragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_vision;
    }

    @Override
    protected void initView() {
        activity.registerReceiver( mGattUpdateReceiver, makeGattUpdateIntentFilter() );
        progressDialog = new ProgressDialog( activity );
        progressDialog.setCancelable( false );
        progressDialog.setMessage( "数据上传中..." );
        edt_odOk.addTextChangedListener( new Watcher( edt_odOk, 25, 2000 ) );
        edt_osOk.addTextChangedListener( new Watcher( edt_osOk, 25, 2000 ) );
        if (PreferencesHelper.getInstance().getInt( getActivity(), Constant.CHART_TYPE, 1 ) == Constant.CHART_STUDENT_NEW) {
            btn_next.setVisibility( View.GONE );
            btn_start.setVisibility( View.VISIBLE );
        } else {
            btn_next.setVisibility( View.VISIBLE );
            btn_start.setVisibility( View.GONE );
        }
        radioGroup.setOnCheckedChangeListener( (group, checkedId) -> glassTypeCheck( checkedId ) );
        rbtnNoGlass.setChecked( true );
    }

    @Override
    protected void initData() {
        if (!EventBus.getDefault().isRegistered( this )) {
            EventBus.getDefault().register( this );
        }
        assert getArguments() != null;
        studentId = getArguments().getString( "studentId" );
        taskId = getArguments().getString( "taskId" );
        taskType = getArguments().getString( "type" );
    }

    @Override
    public void onStart() {
        super.onStart();
        getInfo();
    }

    @OnClick(R.id.btn_next)
    void btn_next() {
        if (TextUtils.isEmpty( BaseApplication.currentEditId )) {
            submitData( "save", true );
        } else {
            submitData( "update", true );
        }
    }

    @OnClick(R.id.btn_start)
    void btn_start() {
        if (PreferencesHelper.getInstance().getInt( getActivity(), Constant.EQUIPMENT ) == 0) {
            peripheralTipDialog = PeripheralTipDialog.newInstance();
            peripheralTipDialog.show( getChildFragmentManager(), "peripheralTipDialog" );
        } else {
            mVisionSelfDialog = VisionSelfDialog.newInstance( 4.5f, daijing1 || daijing2 );
            mVisionSelfDialog.show( getChildFragmentManager(), "mVisionSelfDialog" );
        }
        int glassType = 1;
        if (daijing1) {
            glassType = 2;
        } else if (daijing2) {
            glassType = 3;
        } else if (daijing3) {
            glassType = 4;
        }
        EventBus.getDefault().postSticky( new SocketInput( new Msg.Builder()
                .code( Constant.CODE_START_SUCCESS )
                .size( glassType )
                .mode( PreferencesHelper.getInstance().getInt( getActivity(), Constant.EQUIPMENT ) )
                .value( getDiopter() )
                .chartType( Constant.CHART_STUDENT_NEW )
                .build().toString() ) );
    }

    /**
     * 获取等效球径
     * 测过屈光 直接接口获取  或 戴镜度数/100
     * 都没有传-1
     * （右眼，左眼）示例"0.75,2.5"
     */
    private String getDiopter() {
        StringBuilder sb = new StringBuilder();
        if (rbtnNoGlass.isChecked()) {
            if (rightDiopter.isEmpty()) {
                sb.append( "-1," );
            } else {
                sb.append( Math.abs( Float.parseFloat( rightDiopter ) ) ).append( "," );
            }
            if (leftDiopter.isEmpty()) {
                sb.append( "-1" );
            } else {
                sb.append( Math.abs( Float.parseFloat( leftDiopter ) ) );
            }
        } else if (rbtnFrameGlass.isChecked()) {
            if (rightDiopter.isEmpty()) {
                if (edt_kuangjia_right.getText().toString().isEmpty()) {
                    sb.append( "-1," );
                } else {
                    sb.append( Float.parseFloat( edt_kuangjia_right.getText().toString() ) / 100 ).append( "," );
                }
            } else {
                sb.append( Math.abs( Float.parseFloat( rightDiopter ) ) ).append( "," );
            }
            if (leftDiopter.isEmpty()) {
                if (edt_kuangjia_left.getText().toString().isEmpty()) {
                    sb.append( "-1" );
                } else {
                    sb.append( Float.parseFloat( edt_kuangjia_left.getText().toString() ) / 100 );
                }
            } else {
                sb.append( Math.abs( Float.parseFloat( leftDiopter ) ) );
            }
        } else if (rbtnContactLenses.isChecked()) {
            if (rightDiopter.isEmpty()) {
                if (edt_kuangjia_left.getText().toString().isEmpty()) {
                    sb.append( "-1," );
                } else {
                    sb.append( Float.parseFloat( edt_kuangjia_left.getText().toString() ) / 100 ).append( "," );
                }
            } else {
                rightDiopter = Math.abs( Float.parseFloat( rightDiopter ) ) + "";
                sb.append( Math.abs( Float.parseFloat( rightDiopter ) ) ).append( "," );
            }
            if (leftDiopter.isEmpty()) {
                if (edt_yinxing_left.getText().toString().isEmpty()) {
                    leftDiopter = "-1";
                } else {
                    sb.append( Float.parseFloat( edt_yinxing_left.getText().toString() ) / 100 );
                }
            } else {
                sb.append( Math.abs( Float.parseFloat( leftDiopter ) ) );
            }
        } else if (rbtnOkGlass.isChecked()) {
            if (rightDiopter.isEmpty()) {
                if (edt_odOk.getText().toString().isEmpty()) {
                    sb.append( "-1," );
                } else {
                    sb.append( Float.parseFloat( edt_odOk.getText().toString() ) / 100 ).append( "," );
                }
            } else {
                rightDiopter = Math.abs( Float.parseFloat( rightDiopter ) ) + "";
                sb.append( Math.abs( Float.parseFloat( rightDiopter ) ) ).append( "," );
            }
            if (leftDiopter.isEmpty()) {
                if (edt_osOk.getText().toString().isEmpty()) {
                    sb.append( "-1" );
                } else {
                    sb.append( Float.parseFloat( edt_osOk.getText().toString() ) / 100 );
                }
            } else {
                sb.append( Math.abs( Float.parseFloat( leftDiopter ) ) );
            }
        }
        return sb.toString();
    }

    @OnClick(R.id.btn_connect_device)
    void btn_connect_device() {
        startActivity( DeviceTypeActivity.class );
    }

    /**
     * 选择戴镜类型
     *
     * @param checkedId
     */
    private void glassTypeCheck(int checkedId) {
        setViewClickable( PreferencesHelper.getInstance().getInt( getActivity(), Constant.MODE, 1 ) == Constant.MODE_TEACHER );
        switch (checkedId) {
            case R.id.rbtn_no_glass:
                daijing1 = false;
                daijing2 = false;
                daijing3 = false;
                isContactlenses = 0;
                isFrameglass = 0;
                isOkglasses = 0;
                container_od.setVisibility( View.GONE );
                container_luoyan.setVisibility( View.VISIBLE );
                container_ok.setVisibility( View.GONE );
                tv_lastVision.setVisibility( View.VISIBLE );
                container_kuangjia.setVisibility( View.GONE );
                container_yinxing.setVisibility( View.GONE );
                tv_glass_remark.setVisibility( View.GONE );
                tv_ok_remark.setVisibility( View.GONE );
                changeBottomSave();
                break;
            case R.id.rbtn_frame_glass:
                tv_ok_remark.setVisibility( View.GONE );
                daijing1 = true;
                daijing2 = false;
                daijing3 = false;
                isContactlenses = 0;
                isFrameglass = 1;
                isOkglasses = 0;
                container_od.setVisibility( View.VISIBLE );
                container_luoyan.setVisibility( View.VISIBLE );
                container_ok.setVisibility( View.GONE );
                tv_lastVision.setVisibility( View.VISIBLE );
                container_kuangjia.setVisibility( View.VISIBLE );
                container_yinxing.setVisibility( View.GONE );
                tv_glass_remark.setVisibility( View.VISIBLE );
                changeBottomSave();
                break;
            case R.id.rbtn_contact_lenses:
                tv_ok_remark.setVisibility( View.GONE );
                daijing1 = false;
                daijing2 = true;
                daijing3 = false;
                isContactlenses = 1;
                isFrameglass = 0;
                isOkglasses = 0;
                container_od.setVisibility( View.VISIBLE );
                container_luoyan.setVisibility( View.VISIBLE );
                container_ok.setVisibility( View.GONE );
                tv_lastVision.setVisibility( View.VISIBLE );
                container_yinxing.setVisibility( View.VISIBLE );
                container_kuangjia.setVisibility( View.GONE );
                tv_glass_remark.setVisibility( View.VISIBLE );
                changeBottomSave();
                break;
            case R.id.rbtn_ok_glass:
                daijing1 = false;
                daijing2 = false;
                daijing3 = true;
                isContactlenses = 0;
                isFrameglass = 0;
                isOkglasses = 1;
                container_od.setVisibility( View.VISIBLE );
                container_luoyan.setVisibility( View.GONE );
                container_yinxing.setVisibility( View.GONE );
                container_kuangjia.setVisibility( View.GONE );
                tv_glass_remark.setVisibility( View.VISIBLE );
                tv_lastVision.setVisibility( View.GONE );
                container_ok.setVisibility( View.VISIBLE );
                edt_odOk.addTextChangedListener( new Watcher( edt_odOk, 25, 2000 ) );
                edt_osOk.addTextChangedListener( new Watcher( edt_osOk, 25, 2000 ) );
                changeBottomSave();
                break;
        }
    }


    void setViewClickable(boolean b) {
        odVision.setEnabled( b );
        osVision.setEnabled( b );
        odEyesight.setEnabled( b );
        osEsysight.setEnabled( b );
    }

    @OnClick(R.id.btn_confirm)
    void btn_confirm() {
        if (TextUtils.isEmpty( BaseApplication.currentEditId )) {
            submitData( "save", false );
        } else {
            submitData( "update", false );
        }
    }

    /**
     * 提交数据并保存
     *
     * @time 2020/6/23 14:10
     */

    private void submitData(String submitType, boolean isNext) {
        if (TextUtils.isEmpty( tv_remark.getText().toString() ) && TextUtils.isEmpty( odVision.getText().toString() )
                && TextUtils.isEmpty( osVision.getText().toString() ) && TextUtils.isEmpty( edt_odOk.getText().toString() )
                && TextUtils.isEmpty( edt_osOk.getText().toString() ) && TextUtils.isEmpty( odEyesight.getText().toString() )
                && TextUtils.isEmpty( osEsysight.getText().toString() )) {
            if (isEmptyRemark) {
                Toast.makeText( activity, "请填写视力数据或者备注", Toast.LENGTH_SHORT ).show();
                return;
            }
        }

        String remark = "";
        if (isEmptyRemark) {
            if (isOkglasses == 1) {
                //选中了ok镜
                if (TextUtils.isEmpty( osEsysight.getText().toString() ) || TextUtils.isEmpty( odEyesight.getText().toString() )) {
                    Toast.makeText( activity, "请填写戴镜视力或备注", Toast.LENGTH_SHORT ).show();
                    return;
                }
            } else {
                //没选择ok镜
                if (TextUtils.isEmpty( odVision.getText().toString() ) || TextUtils.isEmpty( osVision.getText().toString() )) {
                    Toast.makeText( activity, "请填写裸眼视力或备注", Toast.LENGTH_SHORT ).show();
                    return;
                }
            }
            String[] strs1 = new String[]{odEyesight.getText().toString(), osEsysight.getText().toString(), odVision.getText().toString(), osVision.getText().toString()};
            //OK镜数组
            String[] strs2 = new String[]{edt_odOk.getText().toString(), edt_osOk.getText().toString()};

            String regSL = "^([3-4].\\d|5.[0-3])$";

            for (String str : strs1) {
                if (!TextUtils.isEmpty( str ) && !str.matches( regSL )) {
                    Toast.makeText( activity, "无法保存,请检查裸眼或戴镜数据格式", Toast.LENGTH_LONG ).show();
                    return;
                }
            }

            for (String str : strs2) {
                if (!TextUtils.isEmpty( str )) {
                    int i;
                    try {
                        i = Integer.parseInt( str );
                        if (i > 2000 || i < 25 || 0 != i % 25) {
                            Toast.makeText( activity, "无法保存, OK镜度数只允许在25~2000范围内，且是25的倍数", Toast.LENGTH_SHORT ).show();
                            return;
                        }
                    } catch (NumberFormatException e) {
                        Toast.makeText( activity, "OK镜数据格式错误, 无法保存", Toast.LENGTH_SHORT ).show();
                        return;
                    }

                }
            }
            /*** 戴镜视力 和裸眼视力 高低的情况 需要放开  并没有 强制限定*/
//            if (daijing1 || daijing2) {
//                if (!TextUtils.isEmpty(odEyesight.getText().toString())) {
//                    //右眼戴镜不为空
//                    Double rightDai = Double.valueOf(odEyesight.getText().toString());
//                    Double rightLuo = Double.valueOf(odVision.getText().toString());
//                    if (rightLuo > rightDai) {
//                        ToastUtil.showToastCenter(mContext, "温馨提示：右眼裸眼视力大于戴镜视力，确认检查是否无误");
////                        return;
//                    }
//                }
//
//                if (!TextUtils.isEmpty(osEsysight.getText().toString())) {
//                    //左眼戴镜不为空
//                    Double leftDai = Double.valueOf(osEsysight.getText().toString());
//                    Double leftLuo = Double.valueOf(osVision.getText().toString());
//                    if (leftLuo > leftDai) {
//                        ToastUtil.showToastCenter(mContext, "温馨提示：左眼裸眼视力大于戴镜视力，确认检查是否无误");
////                        return;
//                    }
//                }
//            }
//            } else {
//                //不选择戴镜
//                if (!TextUtils.isEmpty( odEyesight.getText().toString() )) {
//                    //右眼戴镜不为空，清空数据
//                    odEyesight.setText( "" );
//                }
//
//                if (!TextUtils.isEmpty( osEsysight.getText().toString() )) {
//                    //左眼戴镜不为空
//                    osEsysight.setText( "" );
//                }
//            }
        } else {
            remark = tv_remark.getText().toString().trim();
        }

        if ("update".equals( submitType )) {
            String slbDevice = PreferencesHelper.getInstance().getString( activity, "slbDevice" );
            LogUtil.e( "slb设备类型----", slbDevice );
            RestProxy.getInstance().updateStudentFirstInfo( BaseApplication.currentEditId, studentId + "", isFrameglass + "", isContactlenses + "", isOkglasses + "", osVision.getText().toString(), odVision.getText().toString(), osEsysight.getText().toString(), odEyesight.getText().toString(), edt_odOk.getText().toString(), edt_osOk.getText().toString(), edt_kuangjia_right.getText().toString(), edt_kuangjia_left.getText().toString(), edt_yinxing_right.getText().toString(), edt_yinxing_left.getText().toString(), taskId, remark, manual, slbDevice, new Observer<QualifiedResponse>() {
                @Override
                public void onSubscribe(Disposable d) {
                    progressDialog.show();
                }

                @Override
                public void onNext(QualifiedResponse qualifiedResponse) {
                    if (VisionFragment.this.isAdded()) {
                        progressDialog.dismiss();
                    }
                    if (qualifiedResponse.data) {
                        showQualifiedDialog( false, "屈光度可能均存在异常,建议重新筛查" );
                    } else {
                        if (isNext) {
                            if ("0".equals( taskType )) {
                                ((StudentDetailActivity) activity).setmViewPager( 1 );
                            } else if ("2".equals( taskType )) {
                                ((StudentDetailOtherActivity) activity).setmViewPager( 1 );
                            }

                            EventBus.getDefault().postSticky( new StartVision( 1 ) );
                            getInfo();
                        } else {
                            Toast.makeText( activity, "保存成功", Toast.LENGTH_SHORT ).show();
                            activity.finish();
                        }
                    }
                }

                @Override
                public void onError(Throwable e) {
                    progressDialog.dismiss();
                    e.printStackTrace();
                    NetUtil.onError( e, activity );

                }

                @Override
                public void onComplete() {

                }
            } );
        } else if ("save".equals( submitType )) {
            String slbDevice = PreferencesHelper.getInstance().getString( activity, "slbDevice" );
            RestProxy.getInstance().saveStudentFirstInfo( studentId + "", isFrameglass + "", isContactlenses + "", isOkglasses + "", osVision.getText().toString(), odVision.getText().toString(), osEsysight.getText().toString(), odEyesight.getText().toString(), edt_odOk.getText().toString(), edt_osOk.getText().toString(), edt_kuangjia_right.getText().toString(), edt_kuangjia_left.getText().toString(), edt_yinxing_right.getText().toString(), edt_yinxing_left.getText().toString(), taskId, remark, manual, slbDevice, new Observer<QualifiedResponse>() {
                @Override
                public void onSubscribe(Disposable d) {
                    progressDialog.show();
                }

                @Override
                public void onNext(QualifiedResponse qualifiedResponse) {
                    if (VisionFragment.this.isAdded()) {
                        progressDialog.dismiss();
                    }
                    if (qualifiedResponse.data) {
                        showQualifiedDialog( false, "屈光度可能均存在异常,建议重新筛查" );
                    } else {
                        if (isNext) {
                            if ("0".equals( taskType )) {
                                ((StudentDetailActivity) activity).setmViewPager( 1 );
                            } else if ("2".equals( taskType )) {
                                ((StudentDetailOtherActivity) activity).setmViewPager( 1 );
                            }
                            EventBus.getDefault().postSticky( new StartVision( 1 ) );
                            getInfo();
                        } else {
                            Toast.makeText( activity, "保存成功", Toast.LENGTH_SHORT ).show();
                            activity.finish();
                        }
                    }
                }

                @Override
                public void onError(Throwable e) {
                    progressDialog.dismiss();
                    e.printStackTrace();
                    NetUtil.onError( e, activity );
                }

                @Override
                public void onComplete() {

                }
            } );
        }
    }

    /**
     * 获取学生视力详情
     *
     * @time 2020/6/23 14:11
     */

    private void getInfo() {
        RestProxy.getInstance().getStudentInfoSL( studentId + "", taskId, new Observer<StudentInfoResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(StudentInfoResponse studentInfoResponse) {
                try {
                    if (studentInfoResponse.data.isContactlenses.equals( "1" )) {
                        rbtnContactLenses.setChecked( true );
                        osEsysight.setText( studentInfoResponse.data.osEyesight == null ? "" : studentInfoResponse.data.osEyesight );
                        odEyesight.setText( studentInfoResponse.data.odEyesight == null ? "" : studentInfoResponse.data.odEyesight );
                    }
                    if (studentInfoResponse.data.isFrameglass.equals( "1" )) {
                        rbtnFrameGlass.setChecked( true );
                        osEsysight.setText( studentInfoResponse.data.osEyesight == null ? "" : studentInfoResponse.data.osEyesight );
                        odEyesight.setText( studentInfoResponse.data.odEyesight == null ? "" : studentInfoResponse.data.odEyesight );
                    }
                    if (studentInfoResponse.data.isOkglasses.equals( "1" )) {
                        rbtnOkGlass.setChecked( true );
                        edt_odOk.setText( studentInfoResponse.data.odOk == null ? "" : studentInfoResponse.data.odOk );
                        edt_osOk.setText( studentInfoResponse.data.osOk == null ? "" : studentInfoResponse.data.osOk );
                        osEsysight.setText( studentInfoResponse.data.osEyesight == null ? "" : studentInfoResponse.data.osEyesight );
                        odEyesight.setText( studentInfoResponse.data.odEyesight == null ? "" : studentInfoResponse.data.odEyesight );
                    }
                    BaseApplication.currentEditId = studentInfoResponse.data.id;
                    osVision.setText( studentInfoResponse.data.osVision == null ? "" : studentInfoResponse.data.osVision );
                    odVision.setText( studentInfoResponse.data.odVision == null ? "" : studentInfoResponse.data.odVision );
                    edt_yinxing_left.setText( studentInfoResponse.data.osContactlenses == null ? "" : studentInfoResponse.data.osContactlenses );
                    edt_yinxing_right.setText( studentInfoResponse.data.odContactlenses == null ? "" : studentInfoResponse.data.odContactlenses );
                    edt_kuangjia_left.setText( studentInfoResponse.data.osFrameglass == null ? "" : studentInfoResponse.data.osFrameglass );
                    edt_kuangjia_right.setText( studentInfoResponse.data.odFrameglass == null ? "" : studentInfoResponse.data.odFrameglass );

                    stuName.setText( String.format( "%s  %s", studentInfoResponse.data.fullClassName, studentInfoResponse.data.studentName ) );
                    tv_examiner.setText( String.format( "检查人:%s", studentInfoResponse.data.checker ) );
                    tvExaminerTime.setText( String.format( "检查时间:%s", studentInfoResponse.data.checkedTime ) );
                    if (studentInfoResponse.data.studentLastTaskInfo != null) {
                        studentLastTaskInfo = studentInfoResponse.data.studentLastTaskInfo;
                    }
                    if (!TextUtils.isEmpty( studentInfoResponse.data.remark )) {
//                    if (studentInfoResponse.data.diopterRemark.startsWith("D")) {
//                        tv_remark.setText("其他");
//                        edt_remark.setText(studentInfoResponse.data.diopterRemark.substring(1, studentInfoResponse.data.diopterRemark.length()));
//                        edt_remark.setVisibility(View.VISIBLE);
//                    } else {
                        tv_remark.setTextColor( ContextCompat.getColor( activity, R.color.lightBlack ) );
                        tv_remark.setText( studentInfoResponse.data.remark );
                        isEmptyRemark = false;
//                    }
                    } else {
                        isEmptyRemark = true;
                    }
                    if (studentInfoResponse.data.hasLastChecked == 1) {
                        tv_lastVision.setText( studentInfoResponse.data.lastCheckedYear + "年" + studentInfoResponse.data.lastCheckedMonth + "月筛查记录:右眼(裸眼):" + studentInfoResponse.data.lastOdVision + " 左眼(裸眼):" + studentInfoResponse.data.lastOsVision );
                    } else {
                        tv_lastVision.setText( "" );
                    }

                    changeBottomSave();
                } catch (Exception e) {
                    e.printStackTrace();
                    activity.runOnUiThread( () -> Toast.makeText( activity, "服务器数据异常", Toast.LENGTH_SHORT ).show() );
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtil.onError( e, activity );
            }

            @Override
            public void onComplete() {

            }
        } );

        RestProxy.getInstance().getStudentSEQ( studentId + "", taskId, new Observer<StudentSEQ>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(StudentSEQ studentSEQ) {
                leftDiopter = studentSEQ.data.lSEQ;
                rightDiopter = studentSEQ.data.rSEQ;
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtil.onError( e, activity );
            }

            @Override
            public void onComplete() {

            }
        } );
    }

    @OnClick(R.id.osVision)
    void osVision() {
        showVisionDialog( "左眼裸眼视力", osVision );
    }

    @OnClick(R.id.odVision)
    void odVision() {
        showVisionDialog( "右眼裸眼视力", odVision );

    }

    @OnClick(R.id.osEsysight)
    void osEsysight() {
        showVisionDialog( "左眼戴镜视力", osEsysight );
    }

    @OnClick(R.id.odEyesight)
    void odEyesight() {
        showVisionDialog( "右眼戴镜视力", odEyesight );
    }

    @OnClick(R.id.btn_remark)
    void btn_remark() {
        showRemarkDialog();
    }


    /**
     * 展示视力距离弹框
     *
     * @time 2020/6/23 14:11
     */
    private void showVisionDialog(final String title, final TextView tv) {
        LogUtil.e( "服务是否还在---" + ServiceUtil.isServiceExisted( activity, "com.qdsgjsfk.vision.service.SocketService" ) );
        if (!ServiceUtil.isServiceExisted( activity, "com.qdsgjsfk.vision.service.SocketService" )) {
            activity.stopService( new Intent( activity, SocketService.class ) );
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                activity.startForegroundService( new Intent( activity, SocketService.class ) );
            } else {
                activity.startService( new Intent( activity, SocketService.class ) );
            }
        }
        if (PreferencesHelper.getInstance().getInt( activity, Constant.MODE, Constant.MODE_TEACHER ) == Constant.MODE_STUDENT) {
            //自查模式
            if (TextUtils.isEmpty( tv.getText().toString() )) {
                mVisionSelfDialog = VisionSelfDialog.newInstance( 4.5f, daijing1 );
                EventBus.getDefault().postSticky( new SocketInput( new Msg.Builder().code( Constant.CODE_START_SUCCESS ).chartType( Constant.CHART_STUDENT ).value( "5" ).build().toString() ) );
            } else {
                mVisionSelfDialog = VisionSelfDialog.newInstance( Float.parseFloat( tv.getText().toString() ), daijing1 );
                EventBus.getDefault().postSticky( new SocketInput( new Msg.Builder().code( Constant.CODE_START_SUCCESS ).chartType( Constant.CHART_STUDENT ).value( (int) (Float.parseFloat( tv.getText().toString() ) * 10 - 40) + "" ).build().toString() ) );
            }
            mVisionSelfDialog.show( getChildFragmentManager(), "mVisionSelfDialog" );
            mVisionSelfDialog.setmListener( vision -> {
                EventBus.getDefault().postSticky( new SocketInput( new Msg.Builder().code( Constant.CODE_QUIT ).build().toString() ) );
                manual = "1";
                tv.setText( vision );
                changeBottomSave();
            } );
        } else {
            //医师模式{"code":11,"size":0,"value":"90","chartType":1} 通知从等待页面进入e视标页面
            EventBus.getDefault().postSticky( new SocketInput( new Msg.Builder().code( 11 ).value( 90 + "" ).mode( Constant.MODE_TEACHER ).chartType( PreferencesHelper.getInstance().getInt( activity, Constant.CHART_TYPE, 1 ) ).build().toString() ) );
            String currentVision = tv.getText().toString();

            mVisionDialog = VisionDialog.newInstance( title, getNearVision( tv ) );
            mVisionDialog.show( getChildFragmentManager(), "mVisionDialog" );
            mVisionDialog.setmListener( vision -> {
                EventBus.getDefault().postSticky( new SocketInput( new Msg.Builder().code( Constant.CODE_QUIT ).build().toString() ) );
                manual = "1";
                tv.setText( vision );
                isDataChange = true;
                changeBottomSave();
            } );
        }
//        else if (PreferencesHelper.getInstance().getInt( activity, Constant.MODE, 1 ) == Constant.CHART_TEACHER_E_2_5) {
//            EventBus.getDefault().postSticky( new SocketInput( new Msg.Builder().code( 11 ).value( 90 + "" ).chartType( Constant.CHART_TEACHER_E_2_5 ).build().toString() ) );
//            String currentVision = tv.getText().toString();
//
//            mVisionDialog = mVisionDialog.newInstance( title, getNearVision( tv ) );
//            mVisionDialog.show( getChildFragmentManager(), "mVisionDialog" );
//            mVisionDialog.setmListener( new VisionDialog.OnItemClickListener() {
//                @Override
//                public void onConfirm(String vision) {
//                    EventBus.getDefault().postSticky( new SocketInput( new Msg.Builder().code( 4 ).build().toString() ) );
//                    manual = "1";
//                    tv.setText( vision );
//                    changeBottomSave();
//                }
//            } );
//        }
    }


    /**
     * 显示备注
     *
     * @time 2020/6/23 13:59
     */
    private void showRemarkDialog() {
        if (mRemarkDialog == null) {
            mRemarkDialog = RemarkDialog.newInstance( true, false );
            mRemarkDialog.show( getChildFragmentManager(), "mRemarkDialog" );
            mRemarkDialog.setmListener( (reason, type) -> {
                if (!UtilString.isEmpty( reason )) {
                    isEmptyRemark = false;
                    tv_remark.setTextColor( ContextCompat.getColor( activity, R.color.lightBlack ) );
                    tv_remark.setText( reason );
                    changeBottomSave();
                } else {
                    //清空
                    isEmptyRemark = true;
                    tv_remark.setTextColor( ContextCompat.getColor( activity, R.color.ffd3dcdc ) );
                    tv_remark.setText( "备注：无检测数据必填，否则视为未筛查" );
                    changeBottomSave();
                }

//                    if (type == 1) {
//                        edt_remark.setVisibility(View.GONE);
//                    } else if (type == 2) {
//                        edt_remark.setVisibility(View.VISIBLE);
//                    }
                mRemarkDialog.dismiss();
            } );
        } else if (!mRemarkDialog.isAdded() && !mRemarkDialog.isShowing()) {
            mRemarkDialog.show( getChildFragmentManager(), "mRemarkDialog" );
        }
    }


    /**
     * 检查异常弹框
     *
     * @time 2020/6/23 14:13
     */
    private void showQualifiedDialog(final boolean isNext, String message) {
//        if (mQualifiedDialog == null) {
        mQualifiedDialog = QualifiedDialog.newInstance( message );
        mQualifiedDialog.show( getChildFragmentManager(), "mQualifiedDialog" );
        mQualifiedDialog.setmListener( new QualifiedDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                mQualifiedDialog.dismiss();
            }

            @Override
            public void onCancel() {
                if (isNext) {
                    if ("0".equals( taskType )) {
                        ((StudentDetailActivity) activity).setmViewPager( 1 );
                    } else if ("2".equals( taskType )) {
                        ((StudentDetailOtherActivity) activity).setmViewPager( 1 );
                    }
                    EventBus.getDefault().postSticky( new StartVision( 1 ) );
                    mQualifiedDialog.dismiss();
                } else {
                    activity.finish();
                }
            }
        } );
    }
//        if (!mQualifiedDialog.isAdded() && !mQualifiedDialog.isShowing()) {
//            mQualifiedDialog.show(getChildFragmentManager(), "mQualifiedDialog");
//        }
    //}

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(ModeChange event) {
        if (event.mode == Constant.MODE_TEACHER) {
            btn_next.setVisibility( View.VISIBLE );
            btn_start.setVisibility( View.GONE );
            setViewClickable( true );
        } else {
            btn_next.setVisibility( View.GONE );
            btn_start.setVisibility( View.VISIBLE );
            setViewClickable( false );
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(Msg event) {
        if (event.code == 99) {
            String[] result = event.value.split( "," );
            if (event.size == 1) {
                osVision.setText( result[0] );
                odVision.setText( result[1] );
            } else if (event.size == 2) {
                osVision.setText( result[0] );
                odVision.setText( result[1] );
                if (result.length > 2) {
                    osEsysight.setText( result[0] );
                    odEyesight.setText( result[1] );
                }
            } else if (event.size == 3) {
                osVision.setText( result[0] );
                odVision.setText( result[1] );
                if (result.length > 2) {
                    osEsysight.setText( result[0] );
                    odEyesight.setText( result[1] );
                }
            } else if (event.size == 4) {
                osEsysight.setText( result[0] );
                odEyesight.setText( result[1] );
            }
        }
    }

    private void isQualified(final boolean isNext) {
        RestProxy.getInstance().isQualified( PreferencesHelper.getInstance().getString( activity, "token" ), new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                if (isNext) {
                    Toast.makeText( activity, "保存成功", Toast.LENGTH_SHORT ).show();
                    ((StudentDetailActivity) activity).setmViewPager( 1 );
                    EventBus.getDefault().postSticky( new StartVision( 1 ) );
                    getInfo();
                } else {
                    Toast.makeText( activity, "保存成功", Toast.LENGTH_SHORT ).show();
                    activity.finish();
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();

                NetUtil.onError( e, activity );

            }

            @Override
            public void onComplete() {

            }
        } );
    }

    public void onEventMainThread(Msg event) {


    }

    private void setPhoneFont(TextView tv) {
        if (!BaseApplication.isPad) {
            tv.setTextSize( TypedValue.COMPLEX_UNIT_SP, 14 );
        }
    }

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals( action )) {  //连接成功
                Log.e( "TAG", "Only gatt, just wait" );
            }
//            else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) { //断开连接
//                Toast.makeText(activity, "连接失败", Toast.LENGTH_SHORT).show();
//            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) //可以开始干活了
//            {
//                Toast.makeText(activity, "连接成功", Toast.LENGTH_SHORT).show();
//            }
            else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals( action )) { //收到数据
                Log.e( " ", "RECV DATA" );

                byte[] data = intent.getByteArrayExtra( BluetoothLeService.EXTRA_DATA );

                if (data != null) {
                    if (BaseApplication.strName.startsWith( "CM" )) {
                        float f;
                        DecimalFormat decimalFormat = new DecimalFormat( ".0" );
                        if (!(data[5] == 0) && !(data[5] == 112)) {
                            f = data[5];
                            odVision.setText( decimalFormat.format( f / 10 ) + "" );
                        }
                        if (!(data[6] == 0) && !(data[6] == 112)) {
                            f = data[6];
                            osVision.setText( decimalFormat.format( f / 10 ) + "" );
                        }
                        if (!(data[7] == 0) && !(data[7] == 112)) {
                            f = data[7];
                            odEyesight.setText( decimalFormat.format( f / 10 ) + "" );
                        }
                        if (!(data[8] == 0) && !(data[8] == 112)) {
                            f = data[8];
                            osEsysight.setText( decimalFormat.format( f / 10 ) + "" );
                        }
                        changeBottomSave();
                    }
                }
            }
        }
    };

    public String byte2HexStr(byte[] b) {
        String stmp = "";
        StringBuilder sb = new StringBuilder( "" );
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString( b[n] & 0xFF );
            sb.append( (stmp.length() == 1) ? "0" + stmp : stmp );
            sb.append( " " );
        }
        return sb.toString().toUpperCase().trim();
    }

    private IntentFilter makeGattUpdateIntentFilter() {                        //注册接收的事件
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction( BluetoothLeService.ACTION_GATT_CONNECTED );
        intentFilter.addAction( BluetoothLeService.ACTION_GATT_DISCONNECTED );
        intentFilter.addAction( BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED );
        intentFilter.addAction( BluetoothLeService.ACTION_DATA_AVAILABLE );
        intentFilter.addAction( BluetoothDevice.ACTION_UUID );
        return intentFilter;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach( context );
        activity = (Activity) context;//保存Context引用
    }

    @Override
    public void onDestroy() {
        LogUtil.e( "VisionFragment---", "onDestroy" );
        super.onDestroy();
        EventBus.getDefault().unregister( this );
        activity.unregisterReceiver( mGattUpdateReceiver );
    }

    @Override
    public void onPause() {
        super.onPause();
        //数据变动，提示框是否保存
        if (isDataChange) {

        }
        Log.e( "VisionFragment---", "onPause" );
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.e( "VisionFragment---", "onStop" );
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(BlueTooth event) {
        if (event.type == 4) {
            //用户返回键操作
            if (isDataChange) {
                //数据改动了
            } else {
                //  通知关闭activity
//                EventBus.getDefault().postSticky( new StartVision( 3 ) );
            }
            Log.e( "VisionFragment---", "onMessageEvent" );
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (BaseApplication.lastFragment == 0) {
            notifyBLE( "0000ffe0-0000-1000-8000-00805f9b34fb", "0000ffe1-0000-1000-8000-00805f9b34fb" );
        }
    }

    private void notifyBLE(String uuid_service, String uuid_notify) {
        if (BaseApplication.currentBleDevice == null) {
            return;
        }
        if (bleCount > 2) {
            return;
        }
        BleManager.getInstance().getBluetoothGatt( BaseApplication.currentBleDevice ).requestMtu( 512 );
        BleManager.getInstance().notify(
                BaseApplication.currentBleDevice,
                uuid_service,
                uuid_notify,
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        // 打开通知操作成功
                        System.out.println( "diopater打开通知操作成功" );
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        bleCount++;
                        // 打开通知操作失败
                        System.out.println( "diopater打开通知操作失败" );
                        notifyBLE( "0000181C-0000-1000-8000-00805F9B34FB", "0000C101-0000-1000-8000-00805F9B3402" );
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        tempData = tempData + new String( data );
                        // 打开通知后，设备发过来的数据将在这里出现
                        new Handler().postDelayed( () -> {
                            if (data != null) {
                                if (BaseApplication.strName.startsWith( "CM" )) {
                                    float f;
                                    DecimalFormat decimalFormat = new DecimalFormat( ".0" );
                                    System.out.println( "vision   " + data[5] );
                                    if (!(data[5] == 0) && !(data[5] == 112)) {
                                        f = data[5];
                                        odVision.setText( decimalFormat.format( f / 10 ) + "" );
                                    }
                                    if (!(data[6] == 0) && !(data[6] == 112)) {
                                        f = data[6];
                                        osVision.setText( decimalFormat.format( f / 10 ) + "" );
                                    }
                                    if (!(data[7] == 0) && !(data[7] == 112)) {
                                        f = data[7];
                                        odEyesight.setText( decimalFormat.format( f / 10 ) + "" );
                                    }
                                    if (!(data[8] == 0) && !(data[8] == 112)) {
                                        f = data[8];
                                        osEsysight.setText( decimalFormat.format( f / 10 ) + "" );
                                    }
                                    changeBottomSave();
                                } else {
                                    if (TextUtils.isEmpty( tempData )) {
                                        return;
                                    }
                                    if (tempData.endsWith( "end" )) {
                                        tempData = tempData.substring( 0, tempData.length() - 3 );
                                    }
                                    System.out.println( tempData );
                                    try {
                                        JSONObject object = new JSONObject( tempData );
                                        if (!object.optString( "action" ).equals( "result" )) {
                                            tempData = "";
                                            return;
                                        }
                                        JSONObject payload = (JSONObject) object.opt( "payload" );
                                        odVision.setText( payload.optDouble( "vision_od" ) == 0 ? "" : payload.optDouble( "vision_od" ) + "" );
                                        osVision.setText( payload.optDouble( "vision_os" ) == 0 ? "" : payload.optDouble( "vision_os" ) + "" );
                                        odEyesight.setText( payload.optDouble( "glass_od" ) == 0 ? "" : payload.optDouble( "glass_od" ) + "" );
                                        osEsysight.setText( payload.optDouble( "glass_os" ) == 0 ? "" : payload.optDouble( "glass_os" ) + "" );
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    tempData = "";
                                }
                            }
                        }, 1000 );
                    }
                } );
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint( isVisibleToUser );
        LogUtil.e( "setUserVisibleHint---", isVisibleToUser + "---VisionFragment---" + getUserVisibleHint() );
        if (getUserVisibleHint()) {
            BaseApplication.lastFragment = 0;

//            getInfo();
            notifyBLE( "0000ffe0-0000-1000-8000-00805f9b34fb", "0000ffe1-0000-1000-8000-00805f9b34fb" );
        } else {
//界面不可见 相当于onpause
            BleManager.getInstance().removeNotifyCallback( BaseApplication.currentBleDevice, "0000ffe1-0000-1000-8000-00805f9b34fb" );
        }
    }

    private String getNearVision(TextView tv) {
        try {
            if (tv == odVision) {
                if (TextUtils.isEmpty( tv.getText().toString().trim() )) {
                    if (studentLastTaskInfo.odVision == null) {
                        if (TextUtils.isEmpty( studentLastTaskInfo.age )) {
                            return 4.3 + "";
                        }
                        if (Integer.parseInt( studentLastTaskInfo.age ) > 19) {
                            return 4.2 + "";
                        }
                        if (Integer.parseInt( studentLastTaskInfo.age ) > 14) {
                            return 4.3 + "";
                        }
                        if (Integer.parseInt( studentLastTaskInfo.age ) > 9) {
                            return 4.4 + "";
                        }
                        if (Integer.parseInt( studentLastTaskInfo.age ) > 7) {
                            return 4.5 + "";
                        }
                        if (Integer.parseInt( studentLastTaskInfo.age ) > 0) {
                            return 4.6 + "";
                        }
                    } else {
                        return studentLastTaskInfo.odVision;
                    }
                }
            }
            if (tv == osVision) {
                if (TextUtils.isEmpty( tv.getText().toString().trim() )) {
                    if (studentLastTaskInfo.odVision == null) {
                        if (TextUtils.isEmpty( studentLastTaskInfo.age )) {
                            return 4.3 + "";
                        }
                        if (Integer.parseInt( studentLastTaskInfo.age ) > 19) {
                            return 4.2 + "";
                        }
                        if (Integer.parseInt( studentLastTaskInfo.age ) > 14) {
                            return 4.3 + "";
                        }
                        if (Integer.parseInt( studentLastTaskInfo.age ) > 9) {
                            return 4.4 + "";
                        }
                        if (Integer.parseInt( studentLastTaskInfo.age ) > 7) {
                            return 4.5 + "";
                        }
                        if (Integer.parseInt( studentLastTaskInfo.age ) > 0) {
                            return 4.6 + "";
                        }
                    } else {
                        return studentLastTaskInfo.osVision;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            activity.runOnUiThread( () -> Toast.makeText( activity, "服务器数据异常", Toast.LENGTH_SHORT ).show() );
        }
        return tv.getText().toString().trim();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        View rootView = super.onCreateView( inflater, container, savedInstanceState );
        unbinder = ButterKnife.bind( this, rootView );
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    class Watcher implements TextWatcher {

        EditText etTextView;

        int start, end;

        public Watcher(EditText odR1mm, int start, int end) {
            this.etTextView = odR1mm;
            this.start = start;
            this.end = end;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            String trim = etTextView.getText().toString().trim();
            if (!UtilString.isEmpty( trim )) {
                if (Integer.parseInt( trim ) < start || Integer.parseInt( trim ) > end || (Integer.parseInt( trim ) % 25 != 0)) {
                    tv_ok_remark.setVisibility( View.VISIBLE );
                } else {
                    isDataChange = true;
                    tv_ok_remark.setVisibility( View.GONE );
                }
            } else {
                tv_ok_remark.setVisibility( View.GONE );
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
    }

    void changeBottomSave() {
        LogUtil.e( "是否ok镜---------", isOkglasses + "" );
        if (isEmptyRemark) {
            if (isOkglasses == 1) {
                LogUtil.e( "是否ok镜odEyesight---------", odEyesight.getText().toString().trim() );
                if (!UtilString.isEmpty( odEyesight.getText().toString().trim() ) && !UtilString.isEmpty( osEsysight.getText().toString().trim() )) {
                    //戴镜有数据
                    btn_next.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_blue_stroke ) );
                    btn_next.setTextColor( ContextCompat.getColor( activity, R.color.mainColor ) );
                    btn_confirm.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_blue_button ) );
                    btn_confirm.setTextColor( ContextCompat.getColor( activity, R.color.white ) );

                } else {
                    btn_next.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_grey_stroke_25 ) );
                    btn_next.setTextColor( ContextCompat.getColor( activity, R.color.ffd3dcdc ) );
                    btn_confirm.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_light_blue_button ) );
                    btn_confirm.setTextColor( ContextCompat.getColor( activity, R.color.white ) );
                }

            } else {
                //判断裸眼
                if (!UtilString.isEmpty( odVision.getText().toString().trim() ) && !UtilString.isEmpty( osVision.getText().toString().trim() )) {
                    //裸眼有数据
                    btn_next.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_blue_stroke ) );
                    btn_next.setTextColor( ContextCompat.getColor( activity, R.color.mainColor ) );
                    btn_confirm.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_blue_button ) );
                    btn_confirm.setTextColor( ContextCompat.getColor( activity, R.color.white ) );
                } else {
                    btn_next.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_grey_stroke_25 ) );
                    btn_next.setTextColor( ContextCompat.getColor( activity, R.color.ffd3dcdc ) );
                    btn_confirm.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_light_blue_button ) );
                    btn_confirm.setTextColor( ContextCompat.getColor( activity, R.color.white ) );
                }
            }

        } else {
            btn_next.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_blue_stroke ) );
            btn_next.setTextColor( ContextCompat.getColor( activity, R.color.mainColor ) );
            btn_confirm.setBackground( ContextCompat.getDrawable( activity, R.drawable.item_bg_blue_button ) );
            btn_confirm.setTextColor( ContextCompat.getColor( activity, R.color.white ) );
        }
    }
}
